package edu.gyc.hiwxm.controller;


import edu.gyc.hiwxm.model.Image;
import edu.gyc.hiwxm.service.ImageService;
import edu.gyc.hiwxm.util.FileNameUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@Slf4j
public class UploadController {


    @Autowired
    private ImageService imageService;

    @Value("${ls.file.uploadpath}")
    private String uploadDir;

    @Value("${ls.file.extension}")
     private String  fileExtentions;



    @GetMapping("/upload")
    public String display() {
        return "upload";
    }

    @Transactional
    @PostMapping("/process-upload")
    public String processUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

        if (file.isEmpty()||file.getSize()<=0) {
           redirectAttributes.addFlashAttribute("message","Please select a file to upload");

            return "redirect:upload";
        }
        String fileName=file.getOriginalFilename();
        String fileExt=fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        if(!fileExtentions.contains(fileExt)){
           redirectAttributes.addFlashAttribute("message", "请上传正确的文件类型！");
            return "redirect:upload";
        }


       File saveFile=new File(uploadDir);
        if (!saveFile.exists() && !saveFile.isDirectory()) {
            log.info("目录不存在，则创建目录：" + saveFile);
            saveFile.mkdir();
        }
        String newFileName= FileNameUtil.getRandomFileName() +fileExt;

        String filePath=saveFile.getPath()+File.separator+newFileName;

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath );
             Files.write(path, bytes);

            Image image = new Image();
            image.setPath("/imgs/"+newFileName);
            imageService.save(image);

           redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
        }catch (Exception e) {
           redirectAttributes.addFlashAttribute("message", "An Error Occured " + e.toString() + "'");
            log.error("Error occured {}", e.toString());
        }
        return "redirect:upload";
    }
}
